package com.example.pest.controller.consume;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.pest.bean.PTResult;
import com.example.pest.pojo.*;
import com.example.pest.service.impl.*;
import com.example.pest.service.impl.job.JobRunner;
import com.example.pest.util.JwtUtil;
import com.example.pest.vo.*;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@AllArgsConstructor
@RequestMapping("consume")
public class ConsumeUserController {

    private final XxUserServiceImpl userService;
    private final XxBannerServiceImpl bannerService;
    private final XxRoomServiceImpl roomService;
    private final XxNoticeServiceImpl noticeService;
    private final XxRoomReservationServiceImpl roomReservationService;
    private final XxLiuyanServiceImpl liuyanService;
    private final XxUserReservationServiceImpl userReservationService;

    @GetMapping("/getBannerList")
    public PTResult<List<XxBanner>> getBannerList() {
        List<XxBanner> list = bannerService.lambdaQuery().orderByDesc(XxBanner::getSort).orderByDesc(XxBanner::getId).list();
        return PTResult.ok(list);
    }

    @PostMapping("/updateUserInfo")
    public PTResult updateUserInfo( @RequestBody XxUser user) {
        if (!JwtUtil.getTokenBean().getUserId().equals(user.getId())){
            return PTResult.error("您无权修改他人信息！");
        }
        LambdaUpdateWrapper<XxUser> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(XxUser::getId,user.getId())
                .set(XxUser::getPhone,user.getPhone())
                .set(XxUser::getPassword,user.getPassword())
                .set(XxUser::getSex,user.getSex())
                .set(XxUser::getUsername,user.getUsername());
        if (JwtUtil.isManage()){
            updateWrapper.set(XxUser::getRole,user.getRole());
        }
        userService.update(updateWrapper);
        return PTResult.ok();
    }

    @GetMapping("/getRoomList")
    public PTResult<List<RoomDetail>> getAllRoom(@RequestParam(value = "name",required = false) String name, @RequestParam(value = "canJoin",required = false) Integer canJoin) {
        List<XxRoom> list = roomService.lambdaQuery().like(name != null ,XxRoom::getName,name).or().like(name != null ,XxRoom::getLocal,name).orderByDesc(XxRoom::getId).list();
        List<RoomDetail> roomDetailList = JSONUtil.toList(JSONUtil.toJsonStr(list), RoomDetail.class);
        for (RoomDetail s :roomDetailList){
            s.setCanJoinCount(roomReservationService.lambdaQuery().eq(XxRoomReservation::getRoomId,s.getId()).ge(XxRoomReservation::getCreateTime,DateUtil.beginOfDay(new Date()).getTime()).apply("use_count < zw_count").count());
        }
        if (canJoin != null && canJoin > 0){
            roomDetailList = roomDetailList.stream().filter(s->s.getCanJoinCount() > 0).collect(Collectors.toUnmodifiableList());
        }
        return PTResult.ok(roomDetailList);
    }

    @GetMapping("/getNoticeList")
    public PTResult<List<XxNotice>> getNoticeList() {
        List<XxNotice> list = noticeService.lambdaQuery().orderByDesc(XxNotice::getCreateTime).list();
        return PTResult.ok(list);
    }

    @PostMapping("/yuYue")
    public PTResult yuYue(@RequestBody YuYue yuYue) {
        return roomReservationService.yuYue(JwtUtil.getTokenBean().getUserId(), yuYue.getRoomId(),yuYue.getId()) ? PTResult.ok() : PTResult.error("预约失败，稍后重试！") ;
    }

    @GetMapping("/roomDetail")
    public PTResult<YuYueDetail> roomDetail(@RequestParam long roomId,@RequestParam(required = false) String dateKey) {
        if (dateKey == null){
            dateKey = DateUtil.format(new Date(),"yyyy-MM-dd");
        }
        XxRoom xxRoom = roomService.getById(roomId);
        YuYueDetail detail = JSONUtil.toBean(JSONUtil.toJsonStr(xxRoom),YuYueDetail.class);
        detail.setDateKey(dateKey);
        for (int i=0;i<xxRoom.getPrefixDay();i++){
            String dk = DateUtil.format(DateUtil.offsetDay(new Date(),i),"yyyy-MM-dd");
            detail.pushDateKey(dk);
        }
        for (String span : JobRunner.timeSpan){
            XxRoomReservation reservation =  roomReservationService.lambdaQuery().eq(XxRoomReservation::getRoomId,roomId).eq(XxRoomReservation::getDateKey,dateKey).eq(XxRoomReservation::getTimeSpan,span).one();
            if (reservation != null){
                detail.pushTimeSpan(reservation.getId(),span,reservation.getZwCount(),reservation.getUseCount());
            }else {
                detail.pushTimeSpan(reservation.getId(),span,0,0);
            }
        }
        return PTResult.ok(detail);
    }

    @PostMapping("/pinglun")
    public PTResult pinglun(@RequestBody XxLiuyan content) {
        content.setUserId(JwtUtil.getTokenBean().getUserId());
        content.setCreateTime(new Date());
        noticeService.lambdaUpdate().eq(XxNotice::getId,content.getNoticeId()).setSql("pinglun = pinglun +1").update();
        liuyanService.save(content);
        return PTResult.ok();
    }


    @GetMapping("/pinglun-list")
    public PTResult getNoticeList(@RequestParam long id) {
        List<XxLiuyan> list = liuyanService.lambdaQuery().eq(XxLiuyan::getNoticeId,id).orderByAsc(XxLiuyan::getCreateTime).list();
        List<LiuyanDetail> result = JSONUtil.toList(JSONUtil.toJsonStr(list),LiuyanDetail.class);
        result.forEach(e->{
            XxUser us = userService.getById(e.getUserId());
            e.setName(us.getUsername());
            e.setSex(us.getSex());
        });
        return PTResult.ok(result);
    }


    @GetMapping("/notice-detail")
    public PTResult getNoticeDetail(@RequestParam long id) {
        noticeService.lambdaUpdate().eq(XxNotice::getId,id).setSql("visit = visit +1").update();
        return PTResult.ok(noticeService.getById(id));
    }


    @GetMapping("/yuyueList")
    public PTResult yuyueList() {
        List<XxUserReservation> reservations = userReservationService.lambdaQuery().eq(XxUserReservation::getUserId,JwtUtil.getTokenBean().getUserId()).orderByDesc(XxUserReservation::getId).list();
        List<YuyueInfo> infoList = new ArrayList<>();
        for (XxUserReservation reservation : reservations){
            YuyueInfo info = new YuyueInfo();
            XxRoom room = roomService.getById(reservation.getRoomId());
            info.setName(room.getName());
            info.setPic(room.getPic());
            info.setLocal(room.getLocal());
            info.setTimeSpan(reservation.getTimeSpan());
            info.setDateKey(reservation.getDateKey());
            infoList.add(info);
        }
        return  PTResult.ok(infoList);
    }

}
